package com.krain.ddbb.base;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import com.krain.corelibrary.util.BaseActivityManager;
import com.krain.ddbb.R;
import com.krain.ddbb.activity.LoginActivity;
import com.krain.ddbb.activity.MainActivity;
import com.krain.ddbb.activity.MainActivity_;
import com.krain.ddbb.constant.Constant;
import com.krain.ddbb.constant.Keys;
import com.krain.ddbb.util.BaseUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Class description
 *
 * @author yamin
 * @date 2015/11/2 下午 05:50
 */
@EActivity
public abstract class BaseActivity extends AppCompatActivity {
    @ViewById(R.id.toolbar)
    public Toolbar mToolBar;
    @org.androidannotations.annotations.App
    public APP app;
    @Bean
    protected BaseUtil baseUtil;

    protected BaseActivity mContext;

    HttpReceiver httpReceiver;

    boolean isExit;

    protected ProgressDialog progressDialog;

    @UiThread(propagation = UiThread.Propagation.REUSE)
    @Override
    public void finish() {
        super.finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseActivityManager.getInstance().addActivity(this);
        httpReceiver = new HttpReceiver();
        mContext = this;
    }

    @Override
    protected void onResume() {
        registerReceiver(httpReceiver, new IntentFilter(Constant.ACTION_HTTP_ERRORMSG));
        registerReceiver(httpReceiver, new IntentFilter(Constant.TOKEN_FAILED));
        super.onResume();
    }

    @Override
    protected void onPause() {
        unregisterReceiver(httpReceiver);
        super.onPause();
    }

    @AfterViews
    public void baseAfterViews() {
        initToolBar();
    }

    protected void initToolBar() {
        if (mToolBar == null) return;
        String title = getToolbarTitle();
        mToolBar.setTitle(title == null ? "" : title);
        setSupportActionBar(mToolBar);
        //这里判断如果不是首页的时候就显示返回键
        boolean isMain = BaseActivityManager.getInstance().getTopActivity() instanceof MainActivity;
        if (!isMain) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            mToolBar.setNavigationIcon(R.mipmap.ic_arrow_back);
        }
        setToolbarBackClick(mToolBar);
    }

    private void setToolbarBackClick(Toolbar mToolBar) {
        mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


    }

    /**
     * 显示加载dialog
     */
    @UiThread(propagation = UiThread.Propagation.REUSE)
    public void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(mContext);
            progressDialog.setMessage("正在加载中");
        }
        progressDialog.show();
    }


    @UiThread(propagation = UiThread.Propagation.REUSE)
    public void dismissProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
    }


    public void startAnimActivity(Intent intent, View shareView, String shareElement) {
        ActivityOptionsCompat optionsCompat = ActivityOptionsCompat
                .makeSceneTransitionAnimation(this, shareView, shareElement);
        optionsCompat.makeCustomAnimation(this, android.R.transition.fade, android.R.transition.fade);
        ActivityCompat.startActivity(this, intent, optionsCompat.toBundle());
    }


    public void startActivityForResultOnAnimation(Activity context, Intent intent, int requestCode) {
        baseUtil.startActivityOnAnimation(context, intent, requestCode);
    }


    /**
     * 手机号验证
     *
     * @param number
     * @return
     */
    public static boolean isChinesePhoneNumber(String number) {
        if (TextUtils.isEmpty(number)) {
            return false;
        }

        try {
            Pattern p = Pattern.compile("^1[0-9]{10}$");
            Matcher m = p.matcher(number);
            return m.matches();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 验证手机号码是否合法
     *
     * @param mobile
     * @return
     */
    public boolean validateMobile(String mobile) {
        // 不输入或输入错误手机号
        if (TextUtils.isEmpty(mobile) || !isChinesePhoneNumber(mobile)) {
            return false;
        }
        return true;
    }


    public void showDialog(Context context, String title, String warningMsg, String confirm, String cancel,
                           View.OnClickListener confirmClickListener, View.OnClickListener cancelClickListener, boolean canDismissByUser) {
        baseUtil.showDialog(context, title, warningMsg, confirm, cancel, confirmClickListener, cancelClickListener, canDismissByUser);
    }

    public void closeDialog() {
        baseUtil.closeDialog();
    }


    /**
     * toolbar设置项
     */
    protected abstract String getToolbarTitle();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseActivityManager.getInstance().removeActivity(this);
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode != KeyEvent.KEYCODE_BACK) return super.onKeyDown(keyCode, event);
        if (BaseActivityManager.getInstance().getActivityStackSize() == 1 && this instanceof MainActivity_) {
            if (!isExit) {
                isExit = true;
                baseUtil.showSnackBar(this, "再按一次退出程序");
                revertIsExit();
            } else {
                if (baseUtil.getSnackbar() != null)
                    baseUtil.getSnackbar().dismiss();
                finish();
            }
            return true;
        } else return super.onKeyDown(keyCode, event);

    }

    @UiThread(delay = 3000)
    public void revertIsExit() {
        isExit = false;
    }


    /**
     * Http请求错误信息会传入这个广播显示
     */
    class HttpReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Constant.ACTION_HTTP_ERRORMSG)) {
                //HTTP结果
                baseUtil.showSnackBar(mContext, intent.getStringExtra(Keys.KEY_HTTP_MSG));
                dismissProgressDialog();
            }else if (intent.getAction().equals(Constant.TOKEN_FAILED)){
                baseUtil.showWarningDialog(mContext, "警告", "登陆信息已过期,请重新登录", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        app.clearUserInfo();
                        BaseActivityManager.getInstance().finishAllActivity();
                        LoginActivity.jumpTothisActivity(mContext);
                    }
                });
            }
        }
    }
}
